<template>
  <el-card class="box-card">
  <div slot="header" class="clearfix">
    <span>基本资料</span>
  </div>
  <el-form :model="userForm" status-icon :rules="rules" ref="userFormRule" label-width="100px" class="demo-ruleForm">
        <el-form-item label="登录名称" prop="username">
            <el-input v-model="userForm.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="用户名称" prop="nickname">
            <el-input v-model="userForm.nickname"></el-input>
        </el-form-item>
        <el-form-item label="用户邮箱" prop="email">
            <el-input v-model.number="userForm.email"></el-input>
        </el-form-item>
        <el-form-item>
            <el-button type="primary" @click="submitFn">提交</el-button>
            <el-button @click="resetForm">重置</el-button>
        </el-form-item>
    </el-form>
</el-card>
</template>

<script>
import { updateUserInfoAPI } from '@/api'
import { Message } from 'element-ui'
export default {
  data () {
    return {
      userForm: {
        id: '',
        username: this.$store.state.userInfo.username,
        nickname: '',
        email: ''
      },
      rules: {
        nickname: [
          {
            required: true,
            message: '请输入用户名称',
            trigger: 'blur'
          },
          {
            pattern: /^\S{1,6}$/,
            message: '用户名为1到6位',
            trigger: 'blur'
          }
        ],
        email: [
          {
            required: true,
            message: '请输入用户邮箱',
            trigger: 'blur'
          },
          {
            type: 'email',
            message: '邮箱错误',
            trigger: 'blur'
          }
        ]
      }
    }
  },
  methods: {
    async submitFn () {
      this.$refs.userFormRule.validate(async (valid) => {
        if (valid) {
          console.log(this.userForm)
          // 因为后端接口更新用户资料接口，需要带id过去
          this.userForm.id = this.$store.state.userInfo.id
          const { data: res } = await updateUserInfoAPI(this.userForm)
          if (res.code !== 0) return this.$message.error('更新用户信息失败')
          console.log(res)
          Message.success('更新成功')
          this.$store.dispatch('getUserInfoAction')
          // 向后端发出请求
        } else {
          // 返回错误信息
          Message.error('提交失败')
          return false
        }
      })
    },
    resetForm () {
      this.$refs.userFormRule.resetFields()
    }
  }
}
</script>

<style lang="less" scoped>
.box-card{
    height: 500px;
  .demo-ruleForm{
    width: 500px;
  }
}

</style>
